<template>
  <div class="app-container">
    <el-form :inline="true" :model="par" class="left">
      <el-form-item label="菜单名称">
        <el-input v-model="par.menuName" clearable placeholder="请输入" maxlength="50" />
      </el-form-item>
      <el-form-item label="菜单类型">
        <el-select v-model="par.menuType" placeholder="请选择" clearable>
          <el-option label="目录" value="M" />
          <el-option label="菜单" value="C" />
          <el-option label="接口" value="F" />
          <el-option label="按钮" value="B" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" type="primary" size="small" @click="query">搜 索</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="add(0,{menuId:0,menuName:'根菜单'})"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
    </el-row>
    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="menus"
      class="w100 ofy-auto"
      style="margin-bottom: 20px;"
      row-key="menuId"
      border
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <template slot="empty">
        <el-empty :image-size="100" />
      </template>
      <el-table-column prop="menuName" label="菜单名称" show-overflow-tooltip>
        <template slot-scope="scope">
          <i v-if="menuTypeIconMap[scope.row.menuType].includes('el-icon')" :class="menuTypeIconMap[scope.row.menuType]" />
          <i v-else-if="menuTypeIconMap[scope.row.menuType].includes('iconfont')" :class="menuTypeIconMap[scope.row.menuType]" />
          <svg-icon v-else class="mr5" :icon-class="menuTypeIconMap[scope.row.menuType]" />
          {{ scope.row.menuName }}
          <i v-if="scope.row.visible === 0" class="el-icon-warning red" title="隐藏菜单" />
        </template>
      </el-table-column>
      <el-table-column prop="icon" label="图标" align="center" width="100">
        <template slot-scope="scope">
          <i v-if="scope.row.icon == null || scope.row.icon === ''" />
          <i v-else-if="scope.row.icon.includes('el-icon-')" :class="scope.row.icon" />
          <i v-else-if="scope.row.icon.includes('iconfont')" :class="scope.row.icon" />
          <svg-icon v-else :icon-class="scope.row.icon" />
        </template>
      </el-table-column>
      <el-table-column prop="orderNum" label="排序" align="center" width="60" />
      <el-table-column prop="component" label="路径" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.menuType === 'F'">{{ scope.row.path }}</span>
          <span v-else-if="scope.row.menuType === 'M'">{{ scope.row.path }}</span>
          <span v-else-if="scope.row.menuType === 'B'">{{ scope.row.perVal }}</span>
          <span v-else-if="scope.row.isFrame === 0">{{ scope.row.path }}</span>
          <span v-else>{{ scope.row.component }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="menuType" width="90px" label="菜单类型" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.menuType==='M'">目录</span>
          <span v-if="scope.row.menuType==='C'">菜单</span>
          <span v-if="scope.row.menuType==='F'">接口</span>
          <span v-if="scope.row.menuType==='B'">按钮</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200px" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            circle
            plain
            class="el-icon-edit"
            title="编辑"
            type="primary"
            @click="edit(scope.$index, scope.row)"
          />
          <el-button
            v-if="scope.row.menuType!=='F' && scope.row.menuType!=='B'"
            size="mini"
            circle
            plain
            class="el-icon-plus"
            title="新增"
            type="primary"
            @click="add(scope.$index, scope.row)"
          />
          <el-button
            size="mini"
            circle
            plain
            class="iconfont icon-jiaoseguanli"
            title="授权"
            type="primary"
            @click="showAuthWin(scope.$index, scope.row)"
          />
          <el-button
            size="mini"
            circle
            plain
            class="el-icon-delete"
            title="删除"
            type="danger"
            @click="deleteMenu(scope.$index, scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="菜单授权详情" :visible.sync="auth.show" :append-to-body="true" :close-on-click-modal="false" width="800px">
      <ZlTable v-if="auth.show" ref="authTable" url="/sys/menu/listMenuRight" :param.sync="auth.form" height="400px">
        <template slot="toolbar">
          <el-row>
            <el-button size="small" type="primary" plain icon="el-icon-plus" @click="authAdd.show = true;authAdd.parent=[]">新 增</el-button>
            <el-button size="small" type="danger" plain icon="el-icon-delete" @click="deleteAuths">删 除</el-button>
          </el-row>
        </template>
        <template slot="cols">
          <el-table-column align="center" type="selection" width="50px" />
          <el-table-column align="center" width="50px" type="index" :index="indexMethod" />
          <!--          <el-table-column fixed min-width="100px" prop="rightKey" label="权限标识" align="center" show-overflow-tooltip />
          <el-table-column prop="rightType" label="权限类型" min-width="100px" align="center" show-overflow-tooltip />-->
          <el-table-column prop="orgName" label="授权对象" min-width="100px" align="center" show-overflow-tooltip />
          <el-table-column prop="orgType" label="对象类型" min-width="50px" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-tag v-if="scope.row.orgType ===1" type="warning">用户</el-tag>
              <el-tag v-else-if="scope.row.orgType ===2">部门</el-tag>
              <el-tag v-else-if="scope.row.orgType ===3" type="danger">角色</el-tag>
              <el-tag v-else type="success">未知</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="reject" label="拒绝" width="150px" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-tag v-if="scope.row.reject ===1" type="danger">是</el-tag>
              <el-tag v-else type="success">否</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" min-width="60px">
            <template slot-scope="scope">
              <el-button
                title="删除"
                type="danger"
                circle
                plain
                class="el-icon-delete"
                size="mini"
                @click.native.prevent="deleteAuth([scope.row.id])"
              />
            </template>
          </el-table-column>
        </template>
      </ZlTable>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="auth.show = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="新增菜单授权" :visible.sync="authAdd.show" :append-to-body="true" :close-on-click-modal="false" width="500px">
      <el-form ref="authAddForm" v-loading="authAdd.loading" :model="authAdd.form" :rules="rules" label-width="120px">
        <el-form-item label="是否拒绝" prop="reject">
          <el-switch v-model="authAdd.form.reject" active-color="#ff4949" inactive-color="#409EFF" />
        </el-form-item>
        <el-form-item label="授权对象" prop="orgId" class="is-required">
          <el-tag
            v-for="(o,i) in authAdd.parent"
            :key="i"
            :type="orgTypeColorMap[o.orgType]"
            closable
            class="inline-block m5"
            @close="removeTag(i)"
          >{{ o.orgName }}</el-tag>
          <el-divider v-if="authAdd.parent.length > 0" direction="vertical" />
          <el-button size="small" icon="el-icon-plus" @click="authAdd.showOrgTag = true">添加</el-button>
          <el-button v-show="authAdd.parent.length > 1" size="small" icon="el-icon-close" @click="authAdd.parent = []">清空</el-button>
        </el-form-item>
        <el-form-item label="权限值" prop="objectKey" class="is-required">
          <el-input v-model="authAdd.form.objectKey" clearable autocomplete="off" placeholder="请输入" maxlength="50" readonly />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" :loading="authAdd.loading" @click="saveRight">保 存</el-button>
        <el-button size="small" @click="authAdd.show = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="选择组织结构"
      :visible.sync="authAdd.showOrgTag"
      :append-to-body="true"
      :close-on-click-modal="false"
      width="800px"
      destroy-on-close
      @open="openTag"
    >
      <component :is="orgTag" ref="tag" :multi="true" />
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="addTag">保 存</el-button>
        <el-button size="small" @click="authAdd.showOrgTag = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="addTitle" :visible.sync="win.show" :append-to-body="true" :close-on-click-modal="false" width="700px">
      <el-form ref="editForm" :model="win.form" :rules="rules" :label-width="win.labelWidth">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级菜单" prop="parentId" class="is-required">
              <TreeSelect
                v-model="win.form.parentId"
                :options="menuOptions"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="选择上级菜单"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单名称" prop="menuName" class="is-required">
              <el-input v-model="win.form.menuName" maxlength="50" clearable autocomplete="off" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="menuType">
              <el-radio-group v-model="win.form.menuType">
                <el-radio label="M">目录</el-radio>
                <el-radio label="C">菜单</el-radio>
                <el-radio label="F">接口</el-radio>
                <el-radio label="B">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="win.form.menuType !== 'F' && win.form.menuType !== 'B'" :span="12">
            <el-form-item label="外部链接" prop="isFrame">
              <el-radio-group v-model="win.form.isFrame">
                <el-radio :label="0">是</el-radio>
                <el-radio :label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="win.form.menuType !== 'B'">
            <el-form-item prop="path">
              <span slot="label">
                <el-tooltip content="路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头，接口请求地址：/sys/cache/refreshCache" placement="top">
                  <i class="el-icon-question" />
                </el-tooltip>
                <span v-if="win.form.menuType === 'F'">请求路径</span>
                <span v-else-if="win.form.isFrame === 0">访问地址</span>
                <span v-else>路由地址</span>
              </span>
              <el-input v-model="win.form.path" maxlength="50" clearable autocomplete="off" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="win.form.menuType === 'B'">
            <el-form-item prop="perVal">
              <span slot="label">
                <el-tooltip content="用于控制页面按钮是否可见" placement="top">
                  <i class="el-icon-question" />
                </el-tooltip>
                <span>权限值</span>
              </span>
              <el-input v-model="win.form.perVal" maxlength="50" clearable autocomplete="off" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col v-if="win.form.menuType === 'C' && win.form.isFrame === 1" :span="12">
            <el-form-item prop="component" class="is-required">
              <span slot="label">
                <el-tooltip content="组件路径，如：`system/user/index`，默认在`views`目录下" placement="top">
                  <i class="el-icon-question" />
                </el-tooltip>
                组件路径
              </span>
              <el-input v-model="win.form.component" maxlength="50" placeholder="请输入组件路径" />
            </el-form-item>
          </el-col>
          <el-col v-if="win.form.menuType === 'C' && win.form.isFrame === 1" :span="12">
            <el-form-item prop="query">
              <el-input v-model="win.form.query" placeholder="请输入路由参数" maxlength="255" />
              <span slot="label">
                <el-tooltip content="访问路由的默认传递参数，如：`{&quot;id&quot;: 1, &quot;name&quot;: &quot;ry&quot;}`" placement="top">
                  <i class="el-icon-question" />
                </el-tooltip>
                路由参数
              </span>
            </el-form-item>
          </el-col>
          <el-col v-if="win.form.menuType !== 'F' && win.form.menuType !== 'B'" :span="12">
            <el-form-item label="显示状态" prop="visible">
              <el-radio-group v-model="win.form.visible">
                <el-radio :label="1">显示</el-radio>
                <el-radio :label="0">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="win.form.menuType !== 'F' && win.form.menuType !== 'B'" :span="12">
            <el-form-item label="显示固定" prop="affix">
              <el-radio-group v-model="win.form.affix">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="win.form.menuType === 'C'" :span="12">
            <el-form-item prop="isCache">
              <span slot="label">
                <el-tooltip content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致" placement="top">
                  <i class="el-icon-question" />
                </el-tooltip>
                是否缓存
              </span>
              <el-radio-group v-model="win.form.isCache">
                <el-radio :label="0">缓存</el-radio>
                <el-radio :label="1">不缓存</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="win.form.menuType !== 'F' && win.form.menuType !== 'B'" :span="12">
            <el-form-item label="图标" prop="icon">
              <el-popover
                placement="bottom-start"
                width="460"
                trigger="click"
                @show="$refs['iconSelect'].reset()"
              >
                <IconSelect ref="iconSelect" @selected="selected" />
                <el-input slot="reference" v-model="win.form.icon" placeholder="点击选择图标">
                  <template v-if="win.form.icon">
                    <i slot="prefix" v-if="win.form.icon.includes('el-icon')" :class="win.form.icon" class="md ml10 mr5" style="height: 32px;width: 16px;line-height: 1"/>
                    <i slot="prefix" v-if="win.form.icon.includes('iconfont')" :class="win.form.icon" class="ml10 mr5" style="height: 32px;width: 16px;line-height: 1"/>
                    <svg-icon slot="prefix" v-else class="md ml10 inline-block" :icon-class="win.form.icon" style="height: 32px;width: 16px;"/>
                  </template>
                  <i v-else slot="prefix" class="el-icon-search el-input__icon" />
                </el-input>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="win.form.orderNum" maxlength="50" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" :loading="savingMenu" @click="saveMenu">保 存</el-button>
        <el-button size="small" @click="win.show = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-backtop target=".app-wrapper"></el-backtop>
  </div>
</template>

<script>

import { validator } from '@/utils/form'
import TreeSelect from '@riophae/vue-treeselect'
import { Mixin } from '@/utils/mixin'
import ZlTable from '@/components/table/table-con'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { listMenu, treeMenu, delMenu, saveMenu } from '@/api/menu'
import { deleteRight, saveRight } from '@/api/right'
import IconSelect from '@/components/IconSelect'

export default {
  name: 'Menu',
  mixins: [Mixin],
  components: { TreeSelect, ZlTable, IconSelect },
  data() {
    return {
      menus: [],
      par: {
        menuName: '',
        menuType: null
      },
      selectMenus: [],
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      loading: true,
      refreshTable: true,
      savingMenu: false,
      filterText: '',
      addTitle: '编辑菜单',
      drag: {
        from: '', to: '',
        data: {
          id1: 0,
          id2: null
        },
        show: false
      },
      // 菜单树选项
      menuOptions: [],
      isExpandAll: false,
      win: {
        show: false,
        labelWidth: '100px',
        form: {
          icon: ''
        }
      },
      auth: {
        loading: false,
        show: false,
        form: {
          objectKey: null
        }
      },
      authAdd: {
        parent: [],
        loading: false,
        showOrgTag: false,
        show: false,
        form: {
          objectKey: null, rightKey: 'MENU_RIGHT', rightType: 'YES', reject: false, orgIds: []
        }
      }
    }
  },
  computed: {
    orgTag() {
      return require('/src/components/tag/full-tag').default
    },
    rules() {
      return {
        menuName: [
          { validator: validator('notBlank'), message: '菜单名称不能为空', trigger: ['blur', 'change'] }
        ],
        orderNum: [
          { validator: validator('notBlank'), message: '排序不能为空', trigger: ['blur', 'change'] }
        ],
        parentId: [
          { validator: validator('notBlank'), message: '上级菜单不能为空', trigger: ['blur', 'change'] }
        ],
        sort: [
          { validator: validator('integer_empty'), message: '排序必须为数字值', trigger: ['blur', 'change'] }
        ],
        path: [
          { validator: validator('notBlank'), message: '路由地址不能为空', trigger: ['blur', 'change'] }
        ],
        component: [
          { validator: validator(this.checkComponent), message: '组件路径不能为空', trigger: ['blur', 'change'] }
        ],
        perVal: [
          { validator: validator(this.checkPerVal), message: '权限值不能为空', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    this.query()
  },
  methods: {
    addTag() {
      const p = this.$refs.tag.get()
      if (p.length === 0) {
        this.$message.warning('请选择组织结构')
        return
      }
      // 去重
      const ids = []
      const parent = this.authAdd.parent
      for (let i = 0; i < parent.length; i++) {
        ids.push(parent[i].orgId)
      }
      for (let i = 0; i < p.length; i++) {
        if (ids.indexOf(p[i].orgId) === -1) {
          parent.push(p[i])
        }
      }
      this.authAdd.showOrgTag = false
    },
    openTag() {
      this.$nextTick(() => {
        // this.$refs.tag.clear()
        this.$refs.tag.query()
      })
    },
    saveRight() {
      if (this.authAdd.parent.length === 0) {
        this.$message.warning('请选择组织架构')
        return
      }
      const par = this.$util.copy(this.authAdd.form)
      par.reject = par.reject ? 1 : 0
      par.orgIds = this.authAdd.parent.map(o => o.orgId)
      this.authAdd.loading = true
      saveRight(par).then((r) => {
        this.$message.success('保存成功')
        this.authAdd.loading = false
        this.authAdd.show = false
        this.$refs.authTable.query()
      }).catch(() => {
        this.authAdd.loading = false
      })
    },
    removeTag(i) {
      this.authAdd.parent.splice(i, 1)
    },
    checkComponent() {
      return this.$util.isNotBlank(this.win.form.component) || this.win.form.isFrame !== 1 || this.win.form.menuType !== 'C'
    },
    checkPerVal() {
      return this.$util.isNotBlank(this.win.form.perVal) || this.win.form.menuType !== 'B'
    },
    filterNode(value, data) {
      if (!value) return true
      return data.menuName.indexOf(value) !== -1
    },
    edit(i, row) {
      this.addTitle = '编辑菜单'
      console.log(i, row)
      this.win.form = this.$util.copy(row)
      this.getTreeSelect()
      this.win.show = true
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate()
      })
    },
    getTreeSelect() {
      listMenu().then(response => {
        this.menuOptions = []
        const menu = { menuId: 0, menuName: '根菜单', children: [] }
        menu.children = this.$util.handleTree(response.data, 'menuId')
        this.menuOptions.push(menu)
      })
    },
    indexMethod(index) {
      return (this.$refs.authTable.pageNum - 1) * this.$refs.authTable.pageSize + index + 1
    },
    deleteAuths() {
      const rows = this.$refs.authTable.getSelected()
      if (rows.length === 0) {
        this.$message.warning('请选择数据')
        return
      }
      this.deleteAuth(rows.map(o => o.id))
    },
    deleteAuth(ids) {
      this.auth.loading = true
      this.$confirm('确定要删除权限吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        deleteRight(ids).then(() => {
          this.$message.success('删除成功')
          this.$refs.authTable.query()
        })
      })
    },
    showAuthWin(i, row) {
      this.auth.form.objectKey = row.menuId
      this.authAdd.form.objectKey = row.menuId
      this.auth.show = true
    },
    add(i, row) {
      this.addTitle = '在[' + row.menuName + ']下新增菜单'
      this.reset()
      this.getTreeSelect()
      if (row.menuId) {
        this.win.form.parentId = row.menuId
      } else {
        this.win.form.parentId = 0
      }
      this.win.show = true
    },
    deleteMenu(i, row) {
      this.$confirm('是否删除菜单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(row)
        delMenu(row.menuId).then((result) => {
          console.log(result)
          this.$message.success('删除成功')
          this.win.show = false
          this.query()
        }).catch((e) => {
          this.$message.error(e.message)
        })
      })
    },
    // 选择图标
    selected(name) {
      console.log('selected',name)
      this.win.form.icon = name;
    },
    saveMenu() {
      this.$refs.editForm.validate(r => {
        if (r) {
          this.savingMenu = true
          saveMenu(this.win.form).then((result) => {
            this.savingMenu = false
            this.$message.success('保存成功')
            this.win.show = false
            this.query()
          }).catch(() => {
            this.savingMenu = false
          })
        }
      })
    },
    query() {
      this.loading = true
      treeMenu(this.par).then((res) => {

        this.menus = this.$util.handleTree(res.data, 'menuId')
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.menuId,
        label: node.menuName,
        children: node.children
      }
    },
    reset() {
      this.win.form = {
        menuId: null,
        menuName: '',
        icon: '',
        query: '',
        menuType: 'M',
        parentId: 0,
        isFrame: 1,
        isCache: 0,
        visible: 1,
        affix: 0,
        orderNum: 0,
        component: '',
        path: ''
      }
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate()
      })
    }

  }
}
</script>
<style scoped>

</style>
